package com.u.iot.beauty.service.impl;

import com.u.iot.beauty.service.ISkinService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @program: u-InternetOfThings
 * @description: 皮肤检测业务逻辑类
 * @author: Alex Wu
 * @createDate: 2025-03-24 15:24
 **/

@Slf4j
public class SkinServiceImpl implements ISkinService {

    private List<String> skinDetectionsRequest = new ArrayList<>();
    ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建线程池

    @Override
    public String getDetectionSkinInfo(String skinImageUrl) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(skinDetectionsRequest.size());
        for (String request : skinDetectionsRequest) {
            // 异步调用皮肤检测接口
            try {
                String skinResultItem = asyncCallSkinDetection(request, skinImageUrl, latch);
            }catch(Exception e){
                e.printStackTrace();
                log.error("皮肤检测失败", e);
            }
        }

        // 主线程等待直到所有任务完成
        latch.await();

        // 缓存结果到redis，分钟设置10分钟过期时间
        // redisTemplate.opsForValue().set("skinDetectionResult", "皮肤检测完成", 10, TimeUnit.MINUTES);

        // 结果持久化数据库
        // skinDetectionService.saveSkinDetectionResult(skinDetectionResult);
        return "皮肤检测完成";
    }

    @Override
    public String getDetectionSkinInfoHistory(String uuid) {
        // 从redis上获取缓存结果数据
        return null;
    }

    private String asyncCallSkinDetection(String request, String skinImageUrl, CountDownLatch latch) throws ExecutionException, InterruptedException {

        Future<String> submit = executorService.submit(new Callable<String>() {
            @Override
            public String call() {

                String result = "";
                try {
                    // 模拟任务执行
                    Thread.sleep(1000);
                    // 调用皮肤检测接口
//                 skinDetectionService.detectSkin(request, skinImageUrl);
                    result = "皮肤检测结果";
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    // 任务完成后减少计数
                    latch.countDown();
                }
                return result;
            }
        });

        return submit.get();
    }
}
